<?php
namespace Admin\Controller;
use Think\Controller;
class PaperController extends BaseControlle {
    public function __construct()
    {
        parent::__construct();
    }

    public function index(){
        $this->display();
    }

    //添加考试，逻辑代码部分
    public function NewPaper(){
        $examinationid         = I("post.examinationid",0,'intval');//初始化题库选择
        $examtitle             = I("post.examtitle",'');//试卷标题
        $unit                  = I("post.unit",1,'intval');//做题单位
        $duration              = I("post.duration",0,'intval');//做题时长
        $is_frequency_restrict = I("post.is_frequency_restrict",0,'intval');//是否限制做题次数
        $MaxFrequency          = I("post.MaxFrequency",0,'intval');//做题次数
        $is_startfinish        = I("post.is_startfinish",0,'intval');//是否限制试卷的时间范围
        $startfinish           = I("post.startfinish");//时间范围
        $commentType           = I("post.commentType",0,'intval');//评语类型
        $GradingType           = I("post.GradingType",0,'intval');//评分方式
        $_is_init              = false;


        $exam_assignment = M("exam_assignment");
        $examination     = M("examination");
        $job_library     = M("job_library");
        $exam_topic      = M('exam_topic');

        //题库存在检测
        $if_examinationid = $examination->where("examinationid='$examinationid'")->find();
        if ($if_examinationid && $if_examinationid['status'] != 1){
            $this->ajaxReturn(array('code'=>500,'msg'=>'题库不可用'));
        }elseif($if_examinationid){
            //$this->ajaxReturn(array('code'=>500,'msg'=>'题库号不存在'));
            //检测考试标题，不存在默认和题库标题同步
            if(!$examtitle){
                $examtitle = $if_examinationid['title'];
                $_is_init = true;
            }
        }else{
            if (!$examtitle){
                $this->ajaxReturn(array('code'=>500,'msg'=>'标题和初始化题库，请选择一个填写'));
            }
        }

        //题库数据查出
        $ret_job_library = $job_library->where("examinationid='$examinationid' AND status='1'")->getField('id,sequence',true);
        $starttime  = 0;//开始时间
        $finishtime = 0;//结束时间
        //如果指定时间范围则切割时间范围
        if($is_startfinish == 1){
            //时间切割
            $time = explode('-',$startfinish,2);
            $starttime  = strtotime(trim($time['0']));
            $finishtime = strtotime(trim($time['1']));
        }

        //考试时间检测
        if($duration<1){
            $this->ajaxReturn(array('code'=>500,'msg'=>'请输入考试时间'));
        }else{
            $duration = $duration*60;
        }

        $exam_assignment_db = array(
            'examtitle'=>$examtitle
            ,'examinationid'=>$examinationid
            ,'is_frequency_restrict'=>$is_frequency_restrict
            ,'max_frequency'=>$MaxFrequency
            ,'is_startfinish'=>$is_startfinish
            ,'starttime'=>$starttime
            ,'finishtime'=>$finishtime
            ,'duration'=>$duration
            ,'unit'=>$unit
            ,'comment_type'=>$commentType
            ,'grading_type'=>$GradingType
            ,'teacherid'=>session('uid')
        );
        //添加考试
        $ret_exam_assignment = $exam_assignment->data($exam_assignment_db)->add();

        if(!$ret_exam_assignment){
            $this->ajaxReturn(array('code'=>500,'msg'=>'添加失败'));
        }

        $exam_question_number = M('exam_question_number');
        $db = array(
            'sequence'=>0,
            'title_explain'=>'一、默认大题',
            'exam_assignment_id'=>$ret_exam_assignment
        );
        //添加一个默认的大题
        $ret_exam_question_number = $exam_question_number->data($db)->add();
        if (!$ret_exam_question_number){
            $this->ajaxReturn(array('code'=>500,'msg'=>'默认大题初始化失败，批量添加题目已终止'));
        }

        //判断是否初始化题库
        if($_is_init){
            $ret_exam_topic_error = array();
            $ret_exam_topic       = true;
            //批量添加考试题目
            foreach ($ret_job_library as $item=>$value){
                $ret = $exam_topic->data(array('exam_assignment_id'=>$ret_exam_assignment,'job_library_id'=>$item,'sequence'=>$value['sequence'],'number'=>$value['sequence'],'title_number'=>$ret_exam_question_number))->add();
                if(!$ret){
                    $ret_exam_topic_error[] = $value;
                    $ret_exam_topic = false;
                }
            }
            if ($ret_exam_topic){
                $this->ajaxReturn(array('code'=>200,'msg'=>'添加成功'));
            }else{
                $this->ajaxReturn(array('code'=>200,'msg'=>'试卷创建成功，但是批量添加题目似乎出了些问题'));
            }
        }else{
            $this->ajaxReturn(array('code'=>200,'msg'=>'添加成功'));
        }

    }


    //添加考试的UI
    public function NewPaperUI(){
        $grade             = M("grade");
        $subject_list      = M("subject_list");

        $ret_grade = $grade->select();
        $ret_subject_list = $subject_list->select();
        $this->assign('subject_list',$ret_subject_list);
        $this->assign('grade',$ret_grade);
        $this->display();
    }

    //查询考试题库
    public function selectexaminationid(){
        if(IS_AJAX){
            $subject = I('post.subject',0,'intval');
            $grade   = I('post.grade',0,'intval');
            if($subject==0 || $grade==0){

            }
            $examination = M("examination");
            $ret_examination = $examination->where(array('subject'=>$subject,'grade'=>$grade,'status'=>1))->field('examinationid,title')->select();
            if ($ret_examination){
                $this->ajaxReturn(array('code'=>200,'data'=>$ret_examination));
            }else{
                $this->ajaxReturn(array('code'=>500,'msg'=>'没有相关的题库寸在'));
            }

        }else{
            $this->error('请正确访问');
        }

    }
    //添加考试学生UI
    public function NewPaperStudentUI(){
        $examassignmentid = I('get.examassignmentid',0,'intval');
        $gradegroup = I('gradegroup',0,'intval');
        $DB_PREFIX = C('DB_PREFIX');

        $examassignment = M('exam_assignment');
        $if_examassignment = $examassignment->where(array('id'=>$examassignmentid))->find();
        if(!$if_examassignment){
          $this->ajaxReturn(array('code'=>500,'msg'=>'该考试场次不存在'));
        }elseif ($if_examassignment['unit'] != 1){
            $this->ajaxReturn(array('code'=>500,'msg'=>'该场次非个人类'));
        }
        $grade = M("grade");
        $ret_grade = $grade->select();
        if($gradegroup == 0){
            $gradegroup = $ret_grade[0]['id'];
        }
        $if_grade = $grade->where("id='$gradegroup'")->find();

        if(!$if_grade){
            $this->ajaxReturn(array('code'=>500,'msg'=>'年级组不存在！'));
        }
        //获取年级组学生信息
        $student_information = M('student_information');
        $ret_student_information = $student_information
            ->join("__EXAM_STUDENT__ ON __EXAM_STUDENT__.uid=__STUDENT_INFORMATION__.uid",'LEFT')
            ->field("{$DB_PREFIX}student_information.*,{$DB_PREFIX}exam_student.id as studentexamid,{$DB_PREFIX}exam_student.assignmentid as assignmentid")
            ->where(array('grade'=>$gradegroup))->select();


        $this->assign('grade',$ret_grade);
        $this->assign('examassignmentid',$examassignmentid);
        $this->assign('gradegroup',$gradegroup);
        $this->assign('student_information',$ret_student_information);
        $this->display();
    }

    //添加考试学生逻辑代码
    public function NewPaperStudent(){
        $examassignmentid = I('post.examassignmentid',0,'intval');
        $studentadd         = I('post.studentadd');
        $exam_student = M('exam_student');
        $ret_exam_student = $exam_student->where(array('assignmentid'=>$examassignmentid))->select();

        $is_student = array();
        foreach ($ret_exam_student as $key=>$value){
            if (array_search($value['uid'],$studentadd)){
                $is_student[] = $value['uid'];
            }else{
                $exam_student->where(array('uid'=>$value['uid'],'assignmentid'=>$examassignmentid))->delete();
            }
        }

        $add_student = array();
        //防止空数组
        if($is_student==null){
            $add_student_tmp = $studentadd;
        }else{
            $add_student_tmp = array_diff($studentadd,$is_student);
        }

        //数组去重复
        $add_grade = array_unique($add_student_tmp);

        //往数据库添加数据
        foreach ($add_grade as $k=>$v){
            $exam_student->data(array('uid'=>$v,'assignmentid'=>$examassignmentid))->add();
        }

        $this->ajaxReturn(array('code'=>200));
    }

    //添加考试年级UI
    public function NewPaperGradeUI(){
        $examassignmentid = I('get.examassignmentid',0,'intval');

        $DB_PREFIX = C('DB_PREFIX');

        //检测考试场次是否存在
        $examassignment = M('exam_assignment');
        $if_examassignment = $examassignment->where(array('id'=>$examassignmentid))->find();
        if(!$if_examassignment){
            $this->ajaxReturn(array('code'=>500,'msg'=>'该考试场次不存在'));
        }elseif ($if_examassignment['unit'] != 2){
            $this->ajaxReturn(array('code'=>500,'msg'=>'该场次非年级类'));
        }

        //获取年级组
        $grade = M("grade");
        $ret_grade = $grade->order('number ASC')
            ->join("__EXAM_GRADE__ ON __EXAM_GRADE__.grade=__GRADE__.id",'LEFT')
            ->field("{$DB_PREFIX}grade.*,{$DB_PREFIX}exam_grade.grade as gradeid,{$DB_PREFIX}exam_grade.assignmentid as assignmentid")
            ->select();

        $this->assign('grade',$ret_grade);
        $this->assign('examassignmentid',$examassignmentid);
        $this->display();
    }

    //添加考试年级逻辑代码
    public function NewPaperGrade(){
        $examassignmentid = I('post.examassignmentid',0,'intval');
        $gradeadd         = I('post.gradeadd');
        $exam_grade = M('exam_grade');
        $ret_exam_grade = $exam_grade->where(array('assignmentid'=>$examassignmentid))->select();

        $is_grade = array();

        foreach ($ret_exam_grade as $key=>$value){
            //如果数据存在，则记录；存在则删除
            if(array_search($value['grade'],$gradeadd)){
                $is_grade[] = $value['grade'];
            }else{//存在数据则更新
                $exam_grade->where(array('grade'=>$value['grade'],'assignmentid'=>$examassignmentid))->delete();
            }
        }

        $add_grade = array();
        //防止空数组
        if($is_grade==null){
            $add_grade_tmp = $gradeadd;
        }else{
            $add_grade_tmp = array_diff($gradeadd,$is_grade);
        }

        //数组去重复
        $add_grade = array_unique($add_grade_tmp);
        $ret_exam_grade = true;
        $ret_exam_grade_error = array();

        //往数据库添加数据
        foreach ($add_grade as $k=>$v){
            $ret = $exam_grade->data(array('grade'=>$v,'assignmentid'=>$examassignmentid))->add();
            if(!$ret_exam_grade){
                $ret_exam_grade_error[] = $v;
                $ret_exam_grade = false;
            }
        }

        if($ret_exam_grade){
            $this->ajaxReturn(array('code'=>200,'msg'=>'考试班级数据更新成功'));
        }else{
            $this->ajaxReturn(array('code'=>200,'msg'=>'有可能修改成功，但是系统报告了至少一个错误。',
                'errormsg'=>$ret_exam_grade_error));
        }
    }

    //学生信息查询
    public function SelectStudent(){
        $student_information = M('student_information');
        $DB_PREFIX = C('DB_PREFIX');
        $ret_student_information = $student_information
            ->join("__GRADE__ ON __GRADE__.id=__STUDENT_INFORMATION__.grade",'LEFT')
            ->field("{$DB_PREFIX}student_information.*,{$DB_PREFIX}grade.name as gradename")
            ->select();
        $ret = array(
            'code'=>0,
            'msg'=> "",
            'count'=> 1000,
            'data'=>$ret_student_information);
        $this->ajaxReturn($ret);
    }

    //编辑考试场次信息
    public function EditPaperUI(){
        $examassignmentid = I("get.examassignmentid");
        $examination      = M("examination");
        $exam_assignment  = M("exam_assignment");

        $ret_examination = $examination->where("status=1")->select();
        $ret_exam_assignment = $exam_assignment->where("id='$examassignmentid'")->find();
        //时间，秒转分钟
        $ret_exam_assignment['duration'] = $ret_exam_assignment['duration']/60;
        //判断是否需要切割时间
        if($ret_exam_assignment['starttime'] != 0 || $ret_exam_assignment['finishtime']!= 0){
            //做题时间区间设置
            $ret_exam_assignment['values'] = date('Y/m/d H:i:s',$ret_exam_assignment['starttime'])
                .' - '
                .date('Y/m/d H:i:s',$ret_exam_assignment['finishtime']);
        }else{
            $ret_exam_assignment['values'] = null;
        }

        $this->assign('examination',$ret_examination);
        $this->assign('exam_assignment',$ret_exam_assignment);
        $this->display();
    }

    //编辑考试场次
    public function EditPaper(){
        $exam_assignment_id = I("post.examassignmentid");//考试题库号
        $examtitle             = I("post.examtitle",'');//试卷标题
        $unit                  = I("post.unit",1,'intval');//做题单位
        $duration              = I("post.duration",0,'intval');//做题时长
        $is_frequency_restrict = I("post.is_frequency_restrict",0,'intval');//是否限制做题次数
        $MaxFrequency          = I("post.MaxFrequency",0,'intval');//做题次数
        $is_startfinish        = I("post.is_startfinish",0,'intval');//是否限制试卷的时间范围
        $startfinish           = I("post.startfinish");//时间范围
        $commentType           = I("post.commentType",0,'intval');//评语类型
        $GradingType           = I("post.GradingType",0,'intval');//评分方式


        $exam_assignment = M("exam_assignment");
        $examination     = M("examination");
        $job_library     = M("job_library");

        $if_exam_assignment = $exam_assignment->where(array('id'=>$exam_assignment_id))->find();
        if(!$if_exam_assignment){
            $this->ajaxReturn(array('code'=>500,'msg'=>'考试场次不存在'));
        }
        //标题为空检测
        if(!$examtitle){
            $this->ajaxReturn(array('code'=>500,'msg'=>'标题不能为空'));
        }
        $starttime  = 0;//开始时间
        $finishtime = 0;//结束时间
        //如果指定时间范围则切割时间范围
        if($is_startfinish == 1){
            //时间切割
            $time = explode('-',$startfinish,2);
            $starttime  = strtotime(trim($time['0']));
            $finishtime = strtotime(trim($time['1']));
        }

        //考试时间检测
        if($duration<1){
            $this->ajaxReturn(array('code'=>500,'msg'=>'请输入考试时间'));
        }else{
            $duration = $duration*60;
        }

        $exam_assignment_db = array(
         'examtitle'=>$examtitle
        ,'is_frequency_restrict'=>$is_frequency_restrict
        ,'max_frequency'=>$MaxFrequency
        ,'is_startfinish'=>$is_startfinish
        ,'starttime'=>$starttime
        ,'finishtime'=>$finishtime
        ,'duration'=>$duration
        ,'unit'=>$unit
        ,'comment_type'=>$commentType
        ,'grading_type'=>$GradingType
        ,'teacherid'=>session('uid')
        );

        $ret_exam_assignment = $exam_assignment->where(array('id'=>$exam_assignment_id))->save($exam_assignment_db);
        if ($ret_exam_assignment !== false){
            $this->ajaxReturn(array('code'=>200,'msg'=>'修改成功'));
        }else{
            $this->ajaxReturn(array('code'=>500,'msg'=>'修改失败'));
        }
    }

    /**
     * 考试静态评语设置界面
     */
    public function CommentUI(){
        $assignmentid = I("get.assignmentid",0,'intval');

        $exam_comment = M('exam_comment');
        $ret = $exam_comment->where(array('assignment_id'=>$assignmentid))->order('min ASC')->select();
        $this->assign('ret',$ret);
        $this->assign('assignmentid',$assignmentid);
        $this->display();
    }

    /**
     * 考试静态评语设置
     */
    public function Comment(){
        $assignmentid = I("post.assignmentid",0,'intval');
        $price        = I('post.price',array());

        $min = 0;
        $max = 0;
        $tmp_max = 0;
        $tmp_min = 0;
        $exam_comment = M('exam_comment');

        foreach ($price as $key=>$value){
            //过滤数据
            $price[$key]['min'] = floatval($value['min']);
            $price[$key]['max'] = floatval($value['max']);
            $price[$key]['comment'] = addslashes($value['comment']);
            $price[$key]['assignment_id'] = $assignmentid;

            //记录最小值
            $tmp_min = $tmp_min<$price[$key]['max']?$tmp_max:$price[$key]['min'];
            //记录最大值
            $tmp_max = $tmp_max>$price[$key]['max']?$tmp_max:$price[$key]['max'];
            //统计分数段小的部分和分数段大的部分
            $min += $price[$key]['min'];
            $max += $price[$key]['max'];
        }
        if($tmp_min != 0){
            $this->ajaxReturn(array('code'=>500,'msg'=>'初始最小值为0，不可更改'));
        }
        if ($tmp_max != ($max-$min)){
            $this->ajaxReturn(array('code'=>500,'msg'=>'请按照要求填写评语分数段，分数段需要连续，且前面分数小于后面分数'));
        }

        //删除旧的数据
        $exam_comment->where(array('assignment_id'=>$assignmentid))->delete();
        //添加新的数据
        foreach ($price as $item){
            $exam_comment->data($item)->add();
        }

        $this->ajaxReturn(array('code'=>200));

    }
    //考试管理
    public function Manage(){

        $exam_assignment = M('exam_assignment');

        $page   =      I('get.page');
        $count  =      $exam_assignment->count();
        $page = DBPage($count,30,$page);

        $exam_assignment_ret = $exam_assignment
            //->join("__EXAMINATION__ ON __EXAM_ASSIGNMENT__.examinationid=__EXAMINATION__.examinationid")
            ->join("__USER__ ON __USER__.uid=__EXAM_ASSIGNMENT__.teacherid")
            ->limit(30)
            ->page($page['page'])
            ->order('id desc')
            ->select();
        //print_r($exam_assignment_ret);
        $this->assign('ret',$exam_assignment_ret);
        $this->assign('count',$page['countPage']);
        $this->assign('page',$page['page']);
        $this->display();
    }

    //批阅试卷
    public function ReadOver(){
        $this->display();
    }

    //删除考试场次
    public function DeletePaper(){
        if(IS_AJAX){
            $examassignmentid = I("post.examassignmentid",0,'intval');
            if ($examassignmentid == 0){
                $this->ajaxReturn(array('code'=>500,'msg'=>'请传入参数'));
            }
            $exam_assignment      = M('exam_assignment');
            $exam_question_number = M('exam_question_number');
            $ret_exam_assignment = $exam_assignment->where(array('id'=>$examassignmentid))->delete();
            $ret_exam_question_number = $exam_question_number->where(array('exam_assignment_id'=>$examassignmentid))->delete();
            if($ret_exam_assignment && $ret_exam_question_number){
                $this->ajaxReturn(array('code'=>200));
            }elseif (!$ret_exam_assignment && $ret_exam_question_number){
                $this->ajaxReturn(array('code'=>500,'msg'=>'题库删除失败'));
            }elseif ($ret_exam_assignment && !$ret_exam_question_number){
                $this->ajaxReturn(array('code'=>200,'msg'=>'大题号删除失败'));
            }else{
                $this->ajaxReturn(array('code'=>500,'msg'=>'删除失败'));
            }
        }
    }
}